<template>
    <div class='cart container'>
        <header>
            <van-nav-bar title="购物袋" left-arrow @click-left="$router.back()">
                <template #right>
                    <van-icon v-if="isNavStatus" name="success" @click='isNavBar' />
                    <van-icon v-else name="edit" @click='isNavBar' />
                </template>
            </van-nav-bar>
        </header>
        <section v-if='list.length' ref='wrapper'>
            <div>
                <div class='cart-title'>
                    <van-checkbox @click='checkAllFn' :value="isCheckedAll"></van-checkbox>
                    <span>全选</span>
                </div>
                <ul>
                    <li v-for='(item, index) in list' :key='index'>


                        <div class='check'>
                            <van-checkbox @click='checkItem(index)' v-model="item.checked"></van-checkbox>
                        </div>
                        <van-swipe-cell :before-close="beforeClose">
                            <van-card :price="item.goodsPrice" :title="item.goodsName" class="goods-card"
                                :thumb="item.goodsImgUrl">

                                <template #footer>
                                    <van-stepper @change='changeNum($event, item)' v-model="item.goodsNum" integer />
                                </template>
                            </van-card>

                            <template #right>
                                <van-button square text="删除" type="danger" class="delete-button"
                                    @click='delGoodsFn(item.id)' />
                            </template>
                        </van-swipe-cell>
                    </li>
                </ul>
                <div class="kong"></div>
            </div>
        </section>
        <section v-else ref="wrapper">
            <div class="nothing">
                <van-empty class="custom-image" image="error" description="您的购物袋为空">
                    <van-button round type="danger" class="bottom-button" @click="goHome">继续购物</van-button>
                </van-empty>
            </div>
        </section>
        <footer v-if='list.length'>
            <div class='radio'>
                <van-checkbox @click='checkAllFn' :value="isCheckedAll"></van-checkbox>
            </div>
            <div class='total' v-show='!isNavStatus'>
                <div>
                    共有
                    <span class='total-active'>{{ total.num }}</span>
                    件商品
                </div>
                <div>
                    <span>总计：</span>
                    <span class='total-active'>¥{{ total.price.toFixed(2) }}</span>
                </div>
            </div>
            <div class='order' v-if='isNavStatus' @click='delGoodsFn'>删除</div>
            <div class='order' v-else @click='goOrder'>去结算</div>
       
        </footer>
         <Tabbar></Tabbar>
    </div>
</template>

<script>
import { Toast } from 'vant';
import http from '@/common/api/request.js'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
import Tabbar from '@/components/common/Tabbar.vue';
import BetterScroll from 'better-scroll'
export default {
    name: "Cart",
    data() {
        return {
            isNavStatus: false,
            checked: true,
            BScroll: ''
        };
    },
    created() {
        this.getData();
    },
    computed: {
        ...mapState({
            list: state => state.cart.list,
            selectList: state => state.cart.selectList
        }),
        ...mapGetters(["isCheckedAll", "total"]),
        goodsList() {
            return this.selectList.map(id => {
                return this.list.find(v => v.id == id);
            });
        }
    },
    methods: {
        ...mapMutations(["cartList", "checkItem", "initOrder"]),
        ...mapActions(["checkAllFn", "delGoodsFn"]),
        async getData() {
            let res = await http.$axios({
                url: "/api/selectCart",
                method: "POST",
                headers: {
                    token: true
                }
            });
            res.data.forEach(v => {
                v["checked"] = true;
            });
            this.cartList(res.data);
            console.log(res.data);

            this.$nextTick(() => {
                this.BScroll = new BetterScroll(this.$refs.wrapper, {
                    movable: false,
                    zoom: true,
                    click: true,
                    bounce: true
                })
            })
        },
        // 点击编辑|完成
        isNavBar() {
            this.isNavStatus = !this.isNavStatus;
        },
        // 修改数量
        changeNum(value, item) {
            //当前 购物车商品的 id以及  修改后的数量==》传递给后端
            //value 就是修改后的数量
            //item.id 就是购物车商品的id
            http.$axios({
                url: "/api/updateNum",
                method: "POST",
                headers: {
                    token: true
                },
                data: {
                    id: item.id,
                    num: value
                }
                
            });
        },
        // 结算
        goOrder() {
            if (!this.selectList.length) {
                Toast("请至少选择一件商品");
                return;
            } else if (this.selectList.length > 1){
                Toast("由于特殊原因，单次只可购买单个商品");
                console.log("由于特殊原因，单次只可购买单个商品");
                return;
            }
            let newList = [];
            this.list.forEach(item => {
                this.selectList.filter(v => {
                    if (v == item.id) {
                        newList.push(item);
                    }
                });
            });

            console.log(newList);
            // 生成一个订单
            http.$axios({
                url: "/api/addOrder",
                method: "POST",
                headers: {
                    token: true
                },
                data: {
                    arr: newList
                }
            }).then(res => {
                if (!res.success) return;
                console.log(res.data);
                // 存储订单号
                this.initOrder(res.data);
                // 进入提交订单页面
                this.$router.push({
                    path: "/order",
                    query: {
                        detail: JSON.stringify(this.selectList),
                        goodsList: JSON.stringify(this.goodsList)
                    }
                });
            });
        },
        goHome() {
            this.$router.push('/home')
        },
        beforeClose({ position, instance }) {
            switch (position) {
                case 'left':
                case 'cell':
                case 'outside':
                case 'right':
                    instance.close();
                    break;
            }
        },

    },
    components: { Tabbar }
}
</script>

<style scoped>
header {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    width: 100%;
    height: 1.473333rem;
}

header ::v-deep .van-nav-bar {
    height: 1.473333rem;
}
header ::v-deep .van-nav-bar__content {
    background-color: #fff;
    height: 55px;
}

header ::v-deep .van-nav-bar__title {
    color: #1b1b1b;
    font-size: 18px;
}

header ::v-deep .van-nav-bar .van-icon {
    color: #1b1b1b;
    font-size: 0.593333rem;
}

section {
    background-color: #f5f5f5;
    margin-top: 1.473333rem;
    overflow: hidden;
}

section ul {
    display: flex;
    flex-direction: column;
}

section ul li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 0.533333rem;
    margin: 0.213333rem 0;
    background-color: #fff;
    /* height: 108px; */
}

section ul li img {
    width: 1.973333rem;
    height: 1.973333rem;
}

.check {
    padding-right: 0.373333rem;
}

.cart-title {
    display: flex;
    padding: 0.533333rem;
}

.cart-title span {
    padding: 0 0.4rem;
    font-weight: 500;
    font-size: 0.48rem;
}


::v-deep .van-stepper {
    text-align: right;
}

::v-deep .van-stepper__minus {
    background-color: #fff;
}

::v-deep .van-stepper__plus {
    background-color: #fff;
}

::v-deep .van-stepper__input {
    background-color: #fff;
}

::v-deep .van-checkbox__icon--checked .van-icon {
    background: #1b1b1b;
    background-color: #1b1b1b;
    border-color: #1b1b1b
}

::v-deep .van-checkbox__icon--checked .van-icon {
    background: #1b1b1b;
    background-color: #1b1b1b;
    border-color: #1b1b1b
}

::v-deep .van-card__price-integer {
    font-size: 20px;
}

::v-deep .van-card__title {
    font-size: 14px;
    font-weight: 550;
}

footer {
    position: fixed;
    left: 0;
    bottom: 1.5rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 1.28rem;
    border-top: 0.053333rem solid #ccc;
    background-color: #fff;

}

.radio {
    padding: 0 0.4rem;
}

.radio ::v-deep .van-checkbox__icon--checked .van-icon {
    background: #1b1b1b;
    background-color: #1b1b1b;
    border-color: #1b1b1b
}

.total {
    flex: 1;
    font-size: 0.32rem;
}

.total-active {
    color: #1b1b1b;
}

.order {
    width: 3.2rem;
    line-height: 1.333rem;
    color: #fff;
    text-align: center;
    font-size: 0.426666rem;
    background-color: #1b1b1b;
}

.nothing {
    text-align: center;
    margin-top: 180px;
}

.kong {
    width: 100%;
    height: 2.88rem;
}

.bottom-button {
    width: 160px;
    height: 40px;
    background-color: #1b1b1b;
    border: 1px solid #1b1b1b;
}

.goods-card {
    margin: 0;
    background-color: #fff;
}

.delete-button {
    height: 100%;
    background-color: #ccc;
    border: 1px solid #ccc;
}

::v-deep .van-swipe-cell {
    width: 100%;
    height: 100%;
}

::v-deep .van-dialog__confirm {
    color: #1b1b1b;
}
</style>